package org.eclipse.jdt.internal.ui.callhierarchy;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.jdt.core.IAnnotation;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IMemberValuePair;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;

public class AutoLoadGetterFieldRefactor extends AbstractFieldRefactor implements FieldLombokRefactor {

	public boolean match(IField field) {
		try {
			IAnnotation getter = null;
			IAnnotation[] anns = field.getAnnotations();
			
			for (IAnnotation ann
					: anns) {
				if ("Getter".equals(
						ann.getElementName())) {
					getter = ann;
					break;
				}
			}
			
			if (getter != null) {
				IMemberValuePair[] valuePairs = getter.getMemberValuePairs();
				
				if (valuePairs != null
						&& valuePairs.length > 0) {
					for (IMemberValuePair valuePair
							: valuePairs) {
						String key = valuePair.getMemberName();
						Object value = valuePair.getValue();
						
						if ("autoLoad".equals(key)) {
							// 存在autoLoad,并且值为true
							if (Boolean.TRUE == Boolean.valueOf(value.toString())) {
								return true;
							}
						}
					}
				}
			}
		} catch (Exception e) {
			Logger.info("match异常");
		}
		
		
		return false;
	}

	public void refactor(IField field) throws JavaModelException {
		IType type = field.getDeclaringType();
		
		if (type != null) {
			RefactorClass refactorClass = getRefactorClassBuilder().buildClass(type);
			
			if (refactorClass != null) {
				refactorClass.deleteAnnotation(field, "Getter");
				String fieldName = field.getElementName();
				String fieldType = Signature.toString(field.getTypeSignature()); // TODO ???
				
				Map<String, String> param = new HashMap<String, String>();
				param.put("@fieldName", fieldName);
				param.put("@fieldType", fieldType);
				
				String autoLoadBody = getTemplateEngine().build(TemplateFlag.AUTO_LOAD, param);
				refactorClass.addGetter(fieldName, fieldType, autoLoadBody);
			}
		}
	}

}
